<script setup lang="ts">
import { ref, onMounted } from "vue";
import { message } from "ant-design-vue";
import type {
  SystemNotification,
  SystemNotificationQueryRequest,
} from "../models/systemNotification";

import {
  listSystemNotificationByPage,
  addSystemNotification,
  updateSystemNotification,
  deleteSystemNotification,
} from "../api/systemNotification";
import dayjs from "dayjs";

// 表格数据
const dataSource = ref<SystemNotification[]>([]);
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(6);

// 搜索条件
const searchForm = ref({
  searchText: "",
  title: "",
  content: "",
});

// 编辑弹窗
const editModalVisible = ref(false);
const editingRecord = ref<SystemNotification>({
  id: undefined,
  title: "",
  content: "",
});
const isAdd = ref(false);

// 获取数据列表
const fetchRecords = async () => {
  loading.value = true;
  try {
    const queryRequest: SystemNotificationQueryRequest = {
      current: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm.value,
    };
    const res = await listSystemNotificationByPage(queryRequest);
    if (res.data.code === 0) {
      dataSource.value = res.data.data.records;
      total.value = res.data.data.total;
    } else {
      message.error("获取数据失败");
    }
  } catch (error) {
    message.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 处理表格变化
const handleTableChange = (pagination: any) => {
  currentPage.value = pagination.current;
  pageSize.value = pagination.pageSize;
  fetchRecords();
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchRecords();
};

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    searchText: "",
    title: "",
    content: "",
  };
  currentPage.value = 1;
  fetchRecords();
};

// 添加记录
const handleAdd = () => {
  isAdd.value = true;
  editingRecord.value = {
    id: undefined,
    title: "",
    content: "",
  };
  editModalVisible.value = true;
};

// 编辑记录
const handleEdit = (record: SystemNotification) => {
  isAdd.value = false;
  editingRecord.value = { ...record };
  editModalVisible.value = true;
};

// 保存记录
const handleSave = async () => {
  try {
    if (!editingRecord.value.title || !editingRecord.value.content) {
      message.error("请填写完整信息");
      return;
    }

    if (isAdd.value) {
      const res = await addSystemNotification(editingRecord.value);
      if (res.data.code === 0) {
        message.success("添加成功");
      } else {
        message.error("添加失败");
        return;
      }
    } else {
      const res = await updateSystemNotification(editingRecord.value);
      if (res.data.code === 0) {
        message.success("更新成功");
      } else {
        message.error("更新失败");
        return;
      }
    }
    editModalVisible.value = false;
    fetchRecords();
  } catch (error) {
    message.error("操作失败");
  }
};

// 删除记录
const handleDelete = async (id: number) => {
  try {
    const res = await deleteSystemNotification({ id });
    if (res.data.code === 0) {
      message.success("删除成功");
      fetchRecords();
    } else {
      message.error("删除失败");
    }
  } catch (error) {
    message.error("删除失败");
  }
};

onMounted(() => {
  fetchRecords();
});
</script>

<template>
  <div class="system-notification-management">
    <!-- 搜索表单 -->
    <a-card class="search-card">
      <a-form layout="inline">
        <a-form-item label="搜索">
          <a-input
            v-model:value="searchForm.searchText"
            placeholder="搜索标题或内容"
            allowClear
          />
        </a-form-item>
        <a-form-item label="标题">
          <a-input
            v-model:value="searchForm.title"
            placeholder="请输入标题"
            allowClear
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">搜索</a-button>
            <a-button @click="handleReset">重置</a-button>
            <a-button type="primary" @click="handleAdd">添加通知</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 数据表格 -->
    <a-card class="table-card">
      <a-table
        :dataSource="dataSource"
        :loading="loading"
        :pagination="{
          total,
          current: currentPage,
          pageSize,
          showSizeChanger: true,
          showQuickJumper: true,
        }"
        @change="handleTableChange"
      >
        <a-table-column title="标题" dataIndex="title" />
        <a-table-column title="内容" dataIndex="content" :ellipsis="true" />
        <a-table-column
          title="创建时间"
          dataIndex="createTime"
          :customRender="
            ({ text }) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
          "
        />
        <a-table-column title="操作" key="action">
          <template #default="{ record }">
            <a-space>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除这条通知吗？"
                @confirm="handleDelete(record.id)"
              >
                <a>删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table-column>
      </a-table>
    </a-card>

    <!-- 编辑弹窗 -->
    <a-modal
      v-model:visible="editModalVisible"
      :title="isAdd ? '添加通知' : '编辑通知'"
      @ok="handleSave"
      width="800px"
    >
      <a-form :model="editingRecord" layout="vertical">
        <a-form-item label="标题" required>
          <a-input
            v-model:value="editingRecord.title"
            placeholder="请输入标题"
          />
        </a-form-item>
        <a-form-item label="内容" required>
          <a-textarea
            v-model:value="editingRecord.content"
            :rows="6"
            placeholder="请输入通知内容"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.system-notification-management {
  padding: 24px;
}

.search-card {
  margin-bottom: 24px;
}

.table-card {
  background: #fff;
}

:deep(.ant-card-body) {
  padding: 24px;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-table-cell) {
  vertical-align: top;
}
</style>
